package com.shuo.limit.algorithm;

import com.simba.cache.RedisUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by shuoGG on 2018/9/30
 */
@Component
public class TimeWindowAlgorithm {

    @Autowired
    private RedisUtil redisUtil;

    private static final String SCRIPT_NAME = "script/redis-ratelimit-twnd.lua";

    private Object sha = null;

    @PostConstruct
    public void init() throws IOException {
        try (Jedis jedis = redisUtil.getJedis()) {
            InputStream file = new ClassPathResource(SCRIPT_NAME).getInputStream();
            String script = IOUtils.toString(file);
            sha = jedis.scriptLoad(script);
        }
    }

    public boolean checkAllow(String key, long limit, long interval) {
        try (Jedis jedis = redisUtil.getJedis()) {
            List<String> keys = new ArrayList<>();
            keys.add(key);
            List<String> argS = new ArrayList<>();
            argS.add(Long.toString(limit));
            argS.add(Long.toString(interval));
            argS.add(Long.toString(System.currentTimeMillis()));
            Object ret = jedis.evalsha(sha.toString(), keys, argS);
            return "true".equals(ret);
        }
    }

}
